<template>
  <div></div>
</template>
<script lang="ts" setup>
  // @ts-ignore
  import SockJS from 'sockjs-client/dist/sockjs.min.js';
  import Stomp from 'stompjs';
  import CONFIG from '@/config';
  import { getUnReadMessageCount } from '@/http/api/messagelog';
  import appStore from '@/store';
  import { useRouter } from 'vue-router';

  const emit = defineEmits(['addMsgSize']);

  //请求地址
  const baseUrl = CONFIG.serverAddress + '/ws';
  let stompClient: Stomp.Client | null = null;
  // 重连定时器
  let reconnectTimer: NodeJS.Timeout;
  // 重连间隔时间（单位：毫秒）
  const reconnectInterval = 10000;
  const router = useRouter();
  /**
   * 初始化连接
   */
  const initSocket = () => {
    getUnReadMessageCountAsync();
    con();
  };
  /**
   * 连接
   */
  const con = () => {
    const token = localStorage.getItem('token');
    if (!token || !appStore.useUserInfoStore.userInfo) {
      close();
      return;
    }
    const socket = new SockJS(baseUrl);
    stompClient = Stomp.over(socket);
    // 监听WebSocket关闭事件
    socket.onclose = () => {
      onWebSocketClose();
    };
    const header = {
      Authorization: token
    };
    stompClient.connect(header, connectCallback, onWebSocketError);
    if (stompClient) {
      clearInterval(reconnectTimer);
    }
  };
  const connectCallback = () => {
    const token = localStorage.getItem('token');
    const header = {
      Authorization: token
    };
    if (stompClient) {
      // 在这里执行订阅消息的操作
      stompClient.subscribe(
        '/user/' + appStore.useUserInfoStore.userInfo.id + '/queue/subscribe',
        (message) => {
          const token = localStorage.getItem('token');
          if (!token) {
            close();
            return;
          }
          console.log('Received message:', message.body);
          // 处理收到的消息
          handleMsgSize(-1);
          ElNotification({
            title: '新消息',
            message: '您收到一条回复信息',
            onClick: function () {
              toMyMessageLog();
            },
            type: 'info'
          });
        },
        header
      );
    }
  };

  /**
   * WebSocket关闭回调函数
   */
  const onWebSocketClose = () => {
    console.log('WebSocket connection closed');
    stompClient = null;
    // 开始重连
    reconnectTimer = setTimeout(() => {
      console.log('Reconnecting...');
      con();
    }, reconnectInterval);
  };

  /**
   * WebSocket错误回调函数
   */
  const onWebSocketError = () => {
    console.log('WebSocket connection error');
    stompClient = null;
    // 开始重连
    reconnectTimer = setInterval(() => {
      console.log('Reconnecting...');
      con();
    }, reconnectInterval); // 设置重连间隔时间，单位为毫秒
  };
  /**
   * 断开
   */
  const close = () => {
    if (stompClient) {
      clearInterval(reconnectTimer); // 清除重连定时器
      stompClient.disconnect(() => {
        console.log('Socket disconnected');
      });
      stompClient = null;
    }
  };

  const getUnReadMessageCountAsync = () => {
    const data = getUnReadMessageCount();
    if (data.code === 200) {
      handleMsgSize(data.data);
    }
  };
  const toMyMessageLog = () => {
    router.push('/person/myMessageLog');
  };
  const handleMsgSize = (msgSize: number) => {
    let queryParams = {
      msgSize: msgSize
    };
    emit('addMsgSize', queryParams);
  };
  if (appStore.useUserInfoStore.userInfo) {
    initSocket();
  }
</script>
